package com.icesoft.core.web.controller;

import com.icesoft.core.common.helper.Resp;
import com.icesoft.core.common.util.RegexUtils;
import com.icesoft.core.common.util.UuidUtil;
import com.icesoft.core.web.model.SmsCodeDTO;
import com.icesoft.core.web.service.SmsService;
import com.icesoft.core.web.suppose.safehttp.SafeRequest;
import com.icesoft.core.web.suppose.sms.config.SmsCodeCacheService;
import com.icesoft.core.web.suppose.sms.config.SmsCodePropertySetting;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotEmpty;
import java.util.Random;


/**
 * 短信验证码接口
 */
@RestController
@SafeRequest
@RequestMapping("api/sms")
@Slf4j
@AllArgsConstructor
public class SmsCodeApiController {
    private SmsService smsService;
    private SmsCodePropertySetting smsCodePropertySetting;
    private SmsCodeCacheService smsCodeCacheService;
    private static final String SESSION_CHECK_NAME = UuidUtil.get32UUID();

    /**
     * 发送短信验证码
     */
    @PostMapping(value = "sendCode")
    @ResponseBody
    public Resp<?> smsCode(@NotEmpty String phone, HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (!RegexUtils.isMobile(phone)) {
            return Resp.error("错误的手机号：" + phone);
        }
        SmsCodeDTO codeCache = smsCodeCacheService.getCache(phone);
        if (codeCache == null) {
            Random r = new Random();
            String code = r.nextInt(900000) + 100000 + "";
            codeCache = SmsCodeDTO.builder().code(code).phone(phone).build();
        } else if (session != null) {
            Long lastSendTime = (Long) session.getAttribute(SESSION_CHECK_NAME);
            if (lastSendTime != null && System.currentTimeMillis() - lastSendTime <= smsCodePropertySetting.getSendIntervalSecond() * 1000) {
                return Resp.error("请不要频繁发送");
            }
        }
        codeCache.setCreateTime(System.currentTimeMillis());
        smsCodeCacheService.putCache(phone, codeCache);
        if (session != null) {
            session.setAttribute(SESSION_CHECK_NAME, codeCache.getCreateTime());
        }
        String msg = smsCodePropertySetting.getCodeMsg(codeCache.getCode());
        log.debug("验证码：{}", msg);
        boolean result = smsService.sendSms(phone, msg);
        if (!result) {
            return Resp.error("发送失败");
        }
        return Resp.success();
    }

}
